import 'package:enterprise_v6_app/app/components/custom_refresh.dart';
import 'package:enterprise_v6_app/app/components/regional_organization_tree/regional_organization_tree_view.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/customEndDrawer.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/entities/common/risk_tree_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/double_control/get_tb_base_measures_task_list_entity.dart';
import 'package:enterprise_v6_app/app/modules/application/double_prevention_page/danger_investigation_page/danger_investigation_controller.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';

///隐患排查 任务信息管理
class HazardInvestigationTaskManagementController extends GetxController {
  /// 选中的节点
  RiskTreeEntity selectedEntity = RiskTreeEntity();

  /// 列表刷新key
  final GlobalKey<CustomEasyRefreshListState> globalKey = GlobalKey();

  /// 右侧边栏
  final GlobalKey<ScaffoldState> rightScaffoldKey = GlobalKey();

  /// 筛选后的标题
  String? title = '全部';

  /// 筛选后的层级id  需要筛选后的层级id 默认id ALL
  String levelMeasuresId = 'all';

  /// 筛选后的level 	当前层级:当前层级：全部,1，对象,2，单元,3，事件,4,措施，5
  int? level = 1;

  /// 获取风险数据     "workKindLabel": "日常排查",  "checkCycle": "1",  "checkCycleUnitLabel": null,
  Future<List<GetTbBaseMeasuresTaskListEntity>> getTbBaseMeasuresTaskList(int index, int size, {String? search}) async {
    final res = await HttpUtil().generateGetRequest<List<GetTbBaseMeasuresTaskListEntity>>(
      Interface.getAllTaskByIdAndLevel,
      queryParameters: {
        'id': levelMeasuresId,
        'level': level,
        'pageSize': size,
        'pageNum': index,
      },
    ).execute();
    List<GetTbBaseMeasuresTaskListEntity> list = [];
    res.onSuccess((result) {
      list = result.data!;
    });
    return list;
  }

  /// 筛选按钮
  void onFilterButtonPressed() {
    final DangerInvestigationController controller = Get.find<DangerInvestigationController>();
    controller.filterWidget.value = _filterWidget();
    controller.riskRightScaffoldKey.currentState?.openEndDrawer();
    // rightScaffoldKey.currentState?.openEndDrawer();
  }

  ///点击条目进入详情 任务
  void onItemOnClickDetail(String? id) {
    Get.toNamed(AppRoutes.taskInformationManagementDetails, arguments: id);
  }

  ///add风险措施任务
  void onClickAdd() {
    Get.toNamed(AppRoutes.onClickAddPage, arguments: {'measuresId': levelMeasuresId, 'level': level, 'AddEdit': false});
  }

  ///edit风险措施任务
  void onClickEdit(String? itemId) {
    Get.toNamed(AppRoutes.onClickAddPage, arguments: {'measuresId': levelMeasuresId, 'level': level, 'AddEdit': true, 'itemId': itemId});
  }

  ///删除风险措施任务
  void delTbBaseMeasuresTask(
    String? id,
  ) async {
    final res = await HttpUtil().generatePostRequest(
      Interface.delTbBaseMeasuresTask,
      data: [id],
    ).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        AppToast.show('删除成功');
      }
    });
    res.onError((result) {
      AppToast.showError('删除失败');
    });
    globalKey.currentState?.onRefresh();
  }

  // 重置
  void reset() {
    final DangerInvestigationController controller = Get.find<DangerInvestigationController>();
    controller.riskRightScaffoldKey.currentState?.closeEndDrawer();
    selectedEntity = RiskTreeEntity();
    globalKey.currentState!.onRefresh();
    title = '全部';
    update();
  }

  /// 确定
  void confirm() {
    Get.back();
    //筛选里的任意层级的id
    levelMeasuresId = selectedEntity.id!;
    level = selectedEntity.level!;
    if (selectedEntity.level == 1) {
      title = '全部';
    } else if (selectedEntity.level == 2) {
      title = '全部/${selectedEntity.name}';
    } else {
      title = '${selectedEntity.path}/${selectedEntity.name}';
      if (title != null && title!.startsWith('/')) {
        title = title?.substring(1, title?.length);
        title = '全部/$title';
      }
    }
    globalKey.currentState!.onRefresh();
    update();
  }

  Widget _filterWidget() {
    return CustomEndDrawer(
      centerContext: Column(
        children: [
          RegionalOrganizationTreePage(
            selectedEntity: selectedEntity,
            onCallBack: (RiskTreeEntity entity) {
              selectedEntity = entity;
            },
          ),
        ],
      ),
      reset: reset,
      confirm: confirm,
    );
  }
}
